﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;

namespace EngMp3
{
    public partial class EngMp3 : Form
    {
        public void init()
        {
            Mp3DirEd.Text = @"D:\Webster_142000";
            EngFileEt.Text = @"D:\tdload\eng\词根\英语词汇的奥秘\英语词汇的奥秘.txt";
            WordRegEd.Text = @"^[a-zA-Z]+";
            WordRepeatEd.Text = @"3";
            WordTimeSpaceEd.Text = @"2";
            AimFileEd.Text = @"aim.mp3";
        }

        public EngMp3()
        {
            InitializeComponent();
            init();
        }

        private void Mp3DirBtn_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "请选择音频文件夹：";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                Mp3DirEd.Text = folder.SelectedPath; 
            }
        }

        private void EngFileBtn_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.DefaultExt = "txt";
            file.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
            if (file.ShowDialog() == DialogResult.OK)
            {
                EngFileEt.Text = file.FileName;
            }
        }

        private void JoinMp3Btn_Click(object sender, EventArgs e)
        {
            //最后要合成的音频文件为当前目录下的aim.mp3
            string aimFileName = AimFileEd.Text;
            FileStream aimFS = new FileStream(aimFileName, FileMode.CreateNew, FileAccess.Write);
            BinaryWriter aimBW = new BinaryWriter(aimFS);

            //使用输入流读取单词文本文件
            StreamReader sr = new StreamReader(EngFileEt.Text, Encoding.Default);
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                //使用正则表达式截取字符串
                string word = RegString(line, WordRegEd.Text);
                if (word != null)
                {
                    //将单词对应的音频文件按照重复次数和时间间隔进行拼接
                    Word2Mp3(word, Convert.ToInt32(WordRepeatEd.Text), Convert.ToInt32(WordTimeSpaceEd.Text), aimBW);
                }
            }
            sr.Close();

            aimFS.Close();
            aimBW.Close();
            MessageBox.Show("mp3制作完成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //将单词对应的音频文件按照重复次数和时间间隔写入到最后要合成的音频文件中
        void Word2Mp3(string word, int repeatTimes, int timeSpace, BinaryWriter aimFile)
        {
            byte[] timeSpaceMp3 = TimeSpaceMp3(timeSpace);

            string path = getWrodMp3Path(word);
            byte[] repeatMp3 = RepeatMp3(path, repeatTimes, timeSpaceMp3);
            if (repeatMp3 != null)
            {
                aimFile.Write(repeatMp3);
            }
        }

        //使用正则表达式截取字符串
        public string RegString(string str, string reg)
        {
            Regex r = new Regex(reg); // 定义一个Regex对象实例            
            Match m = r.Match(str); // 在字符串中匹配
            if (m.Success)
            {
                return str.Substring(m.Index, m.Length);
            }
            return null;
        }

        //根据时间生成一个空白mp3文件
        public byte[] TimeSpaceMp3(int timeSpace)
        {
            //1秒空白mp3文件
            string onePath = @"1.mp3";
            byte[] oneBuf = FileMemory(onePath);
            int oneLen = oneBuf.Length;
            byte[] rst = new byte[oneLen * timeSpace];
            for (int i = 0; i < timeSpace; i++)
            {
                Array.Copy(oneBuf, 0, rst, i * oneLen, oneLen);
            }
            return rst;
        }

        //得到某个文件重复播放的内存，包括中间的时间间隔
        public byte[] RepeatMp3(string path, int repeat, byte[] spaceMp3)
        {
            if (repeat < 1 || spaceMp3 == null) return null;

            byte[] oneBuf = FileMemory(path);
            if (oneBuf == null) return null;

            int oneLen = oneBuf.Length;
            int spaceMp3Len = spaceMp3.Length;
            byte[] rst = new byte[(oneLen+spaceMp3Len) * repeat];
            for (int i = 0; i < repeat; i++)
            {
                int len = i * (oneLen + spaceMp3Len);
                Array.Copy(oneBuf, 0, rst, len, oneLen);
                len = i * (oneLen + spaceMp3Len) + oneLen;
                Array.Copy(spaceMp3, 0, rst, len, spaceMp3Len);
            }
            return rst;
        }

        //根据单词，找到音乐文件，并返回内存
        public string getWrodMp3Path(string word)
        {
            string path = word + @".mp3";
            if (File.Exists(path))
                return path;
            else
                path = Mp3DirEd.Text + @"\" + word + @".mp3";

            if (File.Exists(path))
                return path;
            else
            {
                path = Mp3DirEd.Text + @"\" + word.Substring(0, 1) + @"\" + word + @".mp3";               
            }

            if (File.Exists(path))
                return path;

            return null;
        }
        public byte[] WordMp3(string word)
        {
            string path = getWrodMp3Path(word);
            if (path != null)
            {
                return FileMemory(path);
            }
            return null;
        }

        //得到某个文件的二进制内容
        private byte[] FileMemory(string path)
        {
            if (File.Exists(path))
            {
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] buffer = new byte[fs.Length];
                br.Read(buffer, 0, (int)fs.Length);
                fs.Close();
                br.Close();
                return buffer;
            }
            return null;
        }
    }
}